'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/user/kh/freeReceive 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid,appid } = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------
		let freeConfig = await db.collection('a_appid').where({
			appid: appid
		}).get()
		
		res.bean = freeConfig.data[0].freeBean * 1;
		let freeBean = freeConfig.data[0].freeBean * 1;
		let receiveTime = freeConfig.data[0].receiveTime * 1;
		let payMoney = freeConfig.data[0].payMoney * 1;

		if (payMoney > 0) {
			console.log("需付费");
			return res;
		}

		let freeReceiveCount = await db.collection('a_jindou_detail').where({
			user_id: userInfo._id,
			freeReceive: 1
		}).count()

		if (freeReceiveCount.total >= receiveTime) {
			return { state: -1, tips: '已达到最大领取次数' };
		}

		//给用户增加金豆
		let AddBean = await db.collection('uni-id-users').where({
			_id: userInfo._id
		}).update({
			balance: _.inc(freeBean)
		})

		//添加金豆收支明细
		const addBeanDetail = await db.collection('a_jindou_detail').add({
			user_id: userInfo._id,
			nickname: userInfo.nickname,
			change_num: freeBean, //变化的金豆数量
			change_reason: "免费赠送金豆",
			type: "income", //类型：expend:支出,income:收入。
			os_name: originalParam.context.osName || "未知", //用户当时的系统
			appid: userInfo.appid,
			appname: userInfo.appname,
			tfid: userInfo.tfid,
			invite_code: userInfo.invite_code,
			middleman_id: userInfo.middleman_id,
			freeReceive: 1, //此字段标记为免费赠送
			_add_time: new Date().getTime()
		})


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
